package com.fesine.learn.design.pattern.creational.singleton;

/**
 * @description: 懒汉单例模式
 * @author: fesine
 * @createTime:2019/2/20
 * @update:修改内容
 * @author: fesine
 * @updateTime:2019/2/20
 */
public class LazySingleton {
    /**
     * 私有静态变量
     */
    private static LazySingleton lazySingleton = null;

    //也无法阻止通过反射破坏单例
    private static boolean flag = true;

    /**
     * 私有构造器
     */
    private LazySingleton(){
        //在先反射时，此处判断失效
        //if (lazySingleton != null) {
        //    throw new RuntimeException("单例构造器禁止反射调用");
        //}
        //if(flag){
        //    flag =false;
        //}else{
        //    throw new RuntimeException("单例构造器禁止反射调用");
        //}

    }

    //public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
    //    Class c = LazySingleton.class;
    //    Constructor constructor = c.getDeclaredConstructor();
    //    constructor.setAccessible(true);
    //    //v1 正常阻止攻击
    //    LazySingleton o1 = LazySingleton.getInstance();
    //    //v2 升级攻击
    //    Field field = o1.getClass().getDeclaredField("flag");
    //    field.set(o1,true);
    //    LazySingleton o2 = (LazySingleton) constructor.newInstance();
    //    System.out.println(o1);
    //    System.out.println(o2);
    //    System.out.println(o1==o2);
    //}

    /**
     * 创建单例实例
     * 线程不安全
     * @return
     */
    //public static LazySingleton getInstance(){
    //    if(lazySingleton == null){
    //        lazySingleton = new LazySingleton();
    //    }
    //    return lazySingleton;
    //}

    public synchronized static LazySingleton getInstance(){
        if(lazySingleton == null){
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }
}
